﻿using SJ.Platform.EFCore.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SJ.Platform.EFCore.Common
{
    /// <summary>
    /// 事务帮助类
    /// </summary>
    public class TransactionHandle
    {
        /// <summary>
        /// 事务执行操作
        /// </summary>
        /// <typeparam name="TResult"></typeparam>
        /// <param name="action"></param>
        /// <returns></returns>
        public static async Task<TResult> ExecuteInTransactionAsync<TResult>(SJDBContext _context, Func<Task<TResult>> action)
        {
            try
            {
                await _context.Database.BeginTransactionAsync();
                TResult result = await action();
                await _context.Database.CommitTransactionAsync();
                return result;
            }
            catch
            {
                await _context.Database.RollbackTransactionAsync();
                return default;
            }
        }
    }
}
